#include "tcpserver.h"

Data dat;

TcpServer::TcpServer()
{
    mTcpserver = new QTcpServer;

    mTcpsocket = new QTcpSocket;

    mTcpserver->listen(QHostAddress::Any,8080);//监听的端口号

    connect(mTcpserver,SIGNAL(newConnection()),this,SLOT(newConnect()));

    qDebug() << "---init tcp server---";
}


void TcpServer::newConnect()
{
    mTcpsocket = mTcpserver->nextPendingConnection();//设置监听

    connect(mTcpsocket,SIGNAL(readyRead()),this,SLOT(readMessage())); //服务器接收客户端的消息

    connect(mTcpsocket,SIGNAL(disconnected()),mTcpsocket,SLOT(deleteLater()));
}

void TcpServer::readMessage()
{
    bool message;

    QDataStream in(mTcpsocket);

    in.setVersion(QDataStream::Qt_4_8);

    in >> message;

    //qDebug() << "recv heart:" << message;
    dat.heartStatus = message;
}

void TcpServer::sendMessage()
{
    int send = 0;

    QByteArray message;

    QDataStream out(&message,QIODevice::WriteOnly);

    out.setVersion(QDataStream::Qt_4_8);

    out<<send;

    mTcpsocket->write(message);
}
